package com.ruoyi.web.controller.mall;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.UserInfo;
import com.ruoyi.system.domain.vo.MemberQueryVo;
import com.ruoyi.system.mapper.UserInfoMapper;
import com.ruoyi.web.controller.tool.ShortLinkUtil;
import com.ruoyi.web.controller.tool.StreamUtil;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/member")
public class MemberController extends BaseController {

    @Resource
    private UserInfoMapper userInfoMapper;

    private static Integer isDone = 1;

    public static final String url = "8yk.co";

    @GetMapping("/queryList")
    public TableDataInfo queryList(MemberQueryVo vo) {
        startPage();
        List<UserInfo> list = userInfoMapper.selectUserList(vo);
        return getDataTable(list);
    }

    @PostMapping("/export")
    public void userExport(HttpServletResponse response, MemberQueryVo memberQueryVo) {
        List<UserInfo> list = userInfoMapper.selectUserList(memberQueryVo);
        if (list.size()>400000){
            throw new GlobalException("导出数据量过大！");
        }
        ExcelUtil<UserInfo> util = new ExcelUtil<>(UserInfo.class);
        util.exportExcel(response, list, "用户列表");
    }

    /**
     * 导入
     * @param file
     * @return
     */
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean dx, boolean yd, boolean lt){
        if (isDone==1){
            try {
                isDone = 0;
                ExcelUtil<UserInfo> util = new ExcelUtil<>(UserInfo.class);
                AtomicInteger count = new AtomicInteger();
                List<UserInfo> entInfos = null;
                try {
                    entInfos = util.importExcel(file.getInputStream());
                } catch (GlobalException e) {
                    return AjaxResult.error(500,"模板表头名称不匹配");
                }
                do {
                    List<UserInfo> list = new ArrayList<>();
                    for (UserInfo info : entInfos) {
                        if (count.get()>=5000){
                            count.set(0);
                            break;
                        }
                        list.add(info);
                        count.addAndGet(1);
                    }
                    entInfos.removeAll(list);
                    filter(list,dx,yd,lt);
                    list = list.stream().filter(StreamUtil.distinctByKey(UserInfo::getPhone)).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(list)){
                        userInfoMapper.insertBatch(list);
                    }
                    logger.info("剩余:{}",entInfos.size());
                }while (!CollectionUtils.isEmpty(entInfos));
                isDone = 1;
            } catch (Exception e) {
                logger.error("导入失败:{}",e.getMessage());
                return AjaxResult.error(500,"导入失败");
            } finally {
                isDone = 1;
            }
        } else {
            return error("上一批数据未处理完成");
        }
        return success();
    }

    private void filter(List<UserInfo> entInfos,boolean dx,boolean yd,boolean lt){
        List<UserInfo> notRegex = new ArrayList<>();
        List<String> phoneList = new ArrayList<>();
        List<UserInfo> error = new ArrayList<>();
        for (UserInfo entInfo : entInfos) {
            try {
                if (StringUtils.isBlank(entInfo.getPhone())){
                    error.add(entInfo);
                    continue;
                }
                entInfo.setPhone(entInfo.getPhone().replace(" ","").trim());
                if (entInfo.getPhone().contains(",")){
                    String[] split = entInfo.getPhone().split(",");
                    entInfo.setPhone(split[0]);
                }
                if (entInfo.getPhone().contains(";")){
                    String[] split = entInfo.getPhone().split(";");
                    entInfo.setPhone(split[0]);
                }
                phoneList.add(entInfo.getPhone());
                if (!regexPhone(entInfo.getPhone(),dx,yd,lt)){
                    notRegex.add(entInfo);
                }
                String code = ShortLinkUtil.generateUniqueRandomString(7);
                entInfo.setId(IdWorker.getId());
                entInfo.setCode(code);
                entInfo.setUrl(url+"/"+ code);
            } catch (Exception e) {
                error.add(entInfo);
                logger.info("问题数据:{}",entInfo.getPhone());
                logger.info("问题数据:{}",e.getMessage());
            }
        }
        if (!CollectionUtils.isEmpty(notRegex)){
            entInfos.removeAll(notRegex);
        }
        if (!CollectionUtils.isEmpty(error)){
            entInfos.removeAll(error);
        }
        if (!CollectionUtils.isEmpty(phoneList)){
            List<String> repeatCode = userInfoMapper.selectRepeatByPhone(phoneList);
            if (!CollectionUtils.isEmpty(repeatCode)){
                List<UserInfo> repeatList = new ArrayList<>();
                for (UserInfo entInfo : entInfos) {
                    for (String s : repeatCode) {
                        if (entInfo.getPhone().equals(s)){
                            repeatList.add(entInfo);
                            break;
                        }
                    }
                }
                entInfos.removeAll(repeatList);
            }
        }
    }

    private boolean regexPhone(String phone,boolean dx,boolean yd,boolean lt){
        List<String> list = new ArrayList<>();
        if (dx){
            list.addAll(regexPhoneDx());
        }
        if (yd){
            list.addAll(regexPhoneYd());
        }
        if (lt){
            list.addAll(regexPhoneLt());
        }
        String substring = phone.substring(0,3);
        return list.contains(substring);
    }

    private List<String> regexPhoneYd(){
        List<String> list = new ArrayList<>();
        list.add("134");list.add("135");list.add("136");list.add("137");
        list.add("138");list.add("139");list.add("147");list.add("150");
        list.add("151");list.add("152");list.add("157");list.add("158");
        list.add("159");list.add("172");list.add("178");list.add("182");
        list.add("183");list.add("184");list.add("187");list.add("188");
        list.add("195");list.add("197");list.add("198");
        return list;
    }


    private List<String> regexPhoneLt(){
        List<String> list = new ArrayList<>();
        list.add("130");list.add("131");list.add("132");list.add("145");
        list.add("155");list.add("156");list.add("166");list.add("171");
        list.add("175");list.add("176");list.add("185");list.add("186");
        return list;
    }

    private List<String> regexPhoneDx(){
        List<String> list = new ArrayList<>();
        list.add("133");list.add("153");list.add("189");list.add("180");
        list.add("181");list.add("173");list.add("177");list.add("191");
        list.add("199");list.add("149");
        return list;
    }


}
